<?php

namespace app\health\controller;

use app\health\model\HealthOrder;
use app\health\model\HealthPayment;
use app\health\model\HealthUser;
use app\health\model\HealthUserServeRecord;
use app\health\service\WePayService;
use Exception;
use think\Log;

class Notify extends ApiBase
{

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];

    /**
     * 微信支付回调
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function wepay()
    {
        Log::debug('[微信支付回调开始]:START');
        try {
            $params = WePayService::WePayOrder()->getNotify();
            Log::debug('[微信支付回调参数]:' . json_encode($params));
            if (!empty($params['result_code']) && $params['result_code'] === 'SUCCESS') { //支付交易成功
                parse_str($params['attach'], $attach);
                if ($attach['mode'] === 'goods_order') {
                    //商品购买订单
                    $order = HealthOrder::where('order_no', $params['out_trade_no'])->find();
                    if ($order) {
                        HealthOrder::paySuccess($order);
                    }
                }

                if ($attach['mode'] === 'payment') {
                    $payment = HealthPayment::where('out_trade_no', $params['out_trade_no'])->find();
                    if ($payment && $payment->pay_status == 0) {
                        $payment->pay_status     = 1;
                        $payment->pay_time       = time();
                        $payment->transaction_id = $params['transaction_id'];
                        $payment->transaction    = json_encode($params);
                        $payment->save();
                        HealthPayment::paySuccess($payment);
                    }
                }
            }
            return 'SUCCESS';
        } catch (Exception $e) {
            Log::debug('[微信支付回调验签失败]:' . $e->getMessage());
            return 'FAIL';
        }
    }

    /**
     * 接收平安健康服务使用记录
     * @return void
     * @throws \think\Exception
     */
    public function user_serve_record(): void
    {
        $params = request()->param();
        Log::info('[接收平安健康服务使用记录]:' . json_encode($params));
        if (!empty($params['openid']) && strpos($params['openid'], "121") === 0) {
            if (empty($params['order_no'])) {
                $this->error('请传入订单号');
            }
            $mobile = substr($params['openid'], 3);
            $user   = HealthUser::getByMobile($mobile);
            if ($user) {
                HealthUserServeRecord::create([
                    'order_no'       => $params['order_no'] ?? '',
                    'user_id'        => $user->id,
                    'user_mobile'    => $user->mobile,
                    'pajk_openid'    => $params['openid'],
                    'product_code'   => $params['product_code'] ?? '',
                    'service_type'   => $params['service_type'] ?? 0,
                    'use_number'     => $params['use_number'] ?? 0,
                    'surplus_number' => $params['surplus_number'] ?? 0,
                    'use_time'       => $params['use_time'] ?? date('Y-m-d H:i:s'),
                ]);
                queue_custom('app\common\job\WebsiteTaskJob', [
                    'user_id'      => $user['id'],
                    'complete_way' => 3
                ], 0);
            }
            $this->success('success');
        }
        $this->error('未接收到OPENID');
    }
}
